package org.jeecg.modules.message.config;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBoot401Exception;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author tomliu
 * @description: TODO
 * @date 2022/11/2621:09
 */
@Slf4j
@Component
@WebFilter(urlPatterns = { "/sms/*" }, filterName = "tokenAuthorFilter")
public class TokenAuthorFilter implements Filter {
    @Resource
    RedisUtil redisUtil;

    @Override
    public void doFilter(ServletRequest req, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;

        // 在拦截器中，如果请求为OPTIONS请求，则返回true，表示可以正常访问，然后就会收到真正的GET/POST请求
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            log.info("OPTIONS请求，放行");
            chain.doFilter(request, response);
        }
       String path = request.getServletPath();
        if ("/token/getToken".equals(path)) {
            log.info("{} 请求，放行", path);
            chain.doFilter(request, response);
        } else {
            // 验证token
            String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
            if (StringUtils.isBlank(token)) {
                throw new JeecgBoot401Exception("token不能为空!");
            }
            String cacheToken = oConvertUtils.getString(redisUtil.get(CommonConstant.PREFIX_USER_TOKEN + token));
            if (StringUtils.isNotBlank(cacheToken)) {
                if (token.equals(cacheToken)) {
                    chain.doFilter(request, response);
                } else {
                    throw new JeecgBoot401Exception("token非法无效!");
                }
            } else {
                throw new JeecgBoot401Exception("token失效!");
            }
        }
    }

}